﻿var Sprint = {};

Sprint._id = null;
Sprint._taskDataSource = null;
Sprint._developerDataSource = null;
Sprint._savingTasks = false;

/// <summary>Initialize the sprint partial view.</summary>
Sprint.init = function () {
    Sprint._id = $("#SprintId").val();

    // Initialize the start and end input fields as datepickers.
    $("#StartDate").kendoDatePicker();
    $("#EndDate").kendoDatePicker();

    // Get the developers.
    Sprint._developerDataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: _rootUrl + "Home/GetDevelopers/",
                cache: false
            }
        },
        schema: {
            model: {
                id: "DeveloperId",
                fields: {
                    DeveloperId: { type: "number" },
                    Name: { type: "string" },
                    FirstName: { type: "string" },
                    LastName: { type: "string" },
                    Title: { type: "string" }
                }
            }
        }
    });

    // After the developers have been retrieved, get the tasks for the Sprint and populate them in the grid.
    Sprint._developerDataSource.fetch(function () {
        // Get the tasks assigned to the sprint.
        Sprint._taskDataSource = new kendo.data.DataSource({
            transport: {
                read: {
                    url: _rootUrl + "Home/GetSprintTasks/" + Sprint._id,
                    cache: false
                },
                update: {
                    type: "POST",
                    url: _rootUrl + "Home/SaveTasks"
                },
                create: {
                    type: "POST",
                    url: _rootUrl + "Home/SaveTasks"
                },
                destroy: {
                    type: "POST",
                    url: _rootUrl + "Home/SaveTasks?delete=true"
                },
                parameterMap: function (data, type) {
                    // If update, create or destroy, then serialize the data
                    // as JSON so that it can be more easily read on the server.
                    if (type != "read") {
                        return { models: JSON.stringify(data.models) };
                    } else {
                        return data;
                    }
                }
            },
            change: function (e) {
                if (Sprint._savingTasks == true) {
                    // Display the save completed modal window.
                    var window = Sprint.getMessageWindow();
                    window.element.text("The Sprint was successfully saved");
                    window.title("Sprint Saved").center().open();
                    Sprint._savingTasks = false;
                }
            },
            batch: true,
            schema: {
                model: {
                    id: "TaskId",
                    fields: {
                        TaskId: { type: "number" },
                        TypeOfTask: { type: "number" },
                        EstimatedHours: {
                            type: "number",
                            validation: {
                                custom: function (input) {
                                    if (input.length > 0) {
                                        var valid = true;
                                        if (input.val().length > 0) {
                                            valid = input.val() >= 0;
                                            input.attr("data-custom-msg", "The Estimated Hours cannot be negative");
                                        }
                                        return valid;
                                    } else {
                                        return true;
                                    }
                                }
                            }
                        },
                        Description: {
                            type: "string",
                            validation: { required: true }
                        },
                        AssignedToId: { type: "number", defaultValue: 1 },
                        SprintId: { type: "number", defaultValue: Sprint._id },
                        CompletedDate: {
                            type: "date",
                            validation: {
                                required: true,
                                custom: function (input) {
                                    if (input.length > 0) {
                                        var startDate = $("#Start").data("kendoDatePicker").value();
                                        var endDate = $("#End").data("kendoDatePicker").value();
                                        var completedDate = new Date(input.val());
                                        input.attr("data-custom-msg", "The Completed Date should be between the Start Date and the End Date");
                                        return (completedDate >= startDate && completedDate <= endDate);
                                    } else {
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });

        // Display the tasks assigned to a sprint in a grid.
        $("#taskGrid").kendoGrid({
            dataSource: Sprint._taskDataSource,
            height: 400,
            editable: true,
            toolbar: ["create"],
            columns: [{
                field: "TypeOfTask",
                title: "Type",
                template: "#= TypeOfTask == 1 ? 'Scenerio' : 'Change Request' #",
                width: "200px",
                editor: function (container, options) {
                    $("<input />")
                        .attr("data-bind", "value:TypeOfTask")
                        .appendTo(container)
                        .kendoDropDownList({
                            dataSource: [
                                { text: "Scenerio", value: "1" },
                                { text: "Change Request", value: "2" }
                            ],
                            dataTextField: "text",
                            dataValueField: "value"
                        });
                }
            }, {
                field: "Description"
            }, {
                field: "AssignedToId",
                title: "Assigned To",
                template: "#= Sprint.sprintGrid_displayPerson(AssignedToId) #",
                editor: function (container, options) {
                    // Setup the hidden field for the value.
                    var dropdown = $("<input />")
                        .attr("id", "AssignedToIdDropDownList")
                        .attr("data-bind", "value:AssignedToId")
                        .appendTo(container)
                        .kendoDropDownList({
                            dataSource: Sprint._developerDataSource,
                            template: "<table><tr><td width='100px'>${ FirstName }</td><td width='100px'>${ LastName }</td><td width='100px'>${ Title }</td></tr></table>",
                            dataValueField: "DeveloperId",
                            dataTextField: "Name"
                        });

                    // Display column headings for the dropdown list.
                    if ($("#AssignedToIdDropDownList-listHeading").length == 0) {
                        $("<div/>")
                            .attr("id", "AssignedToIdDropDownList-listHeading")
                            .html("<table><tr><td width='100px'><b>First Name</b></td><td width='100px'><b>Last Name</b></td><td width='100px'><b>Title</b></td></tr></table>")
                            .prependTo($("#AssignedToIdDropDownList-list"));
                    }
                }
            }, {
                field: "EstimatedHours",
                title: "Estimated Hours"
            }, {
                field: "CompletedDate",
                title: "Completed",
                template: "#= kendo.toString(CompletedDate, 'MM/dd/yyyy') #"
            }, {
                command: "destroy",
                title: " ",
                width: "110px"
            }]
        });
    });

    // Initialize the Save button.
    $("#saveButton").click(Sprint.save);
}

/// <summary>Based on the id passed in, determine which person's name to display in the grid.</summary>
Sprint.sprintGrid_displayPerson = function (id) {
    var person = Sprint._developerDataSource.get(id);
    if (person == undefined) {
        return "";
    } else {
        return person.Name;
    }
}

/// <summary>Save the sprint information.  Then save the sprint tasks.</summary>
Sprint.save = function () {
    $.ajax({
        type: "POST",
        dataType: "json",
        data: $("#sprintForm").serialize(),
        url: _rootUrl + "Home/UpdateSprint"
    })
    .done(function (result) {
        if (result.message.length == 0) {
            // Tell the task data source to save all pending changes.
            Sprint._savingTasks = true;
            Sprint._taskDataSource.sync();
        } else {
            // Display the error in a modal window.
            var window = Sprint.getMessageWindow();
            window.element.text(result.message);
            window.title("Sprint Save Error").center().open();
        }
    })
    .fail(function () {
        alert("fail");
    });
}

Sprint.getMessageWindow = function () {
    var messageWindow = $("#messageWindow");
    var kendoWindow = messageWindow.data("kendoWindow");

    // Has the kendoWindow been created yet?
    if (kendoWindow == undefined) {
        // Create the kendoWindow.
        kendoWindow = messageWindow.kendoWindow({
            height: "200px",
            width: "300px",
            draggable: false,
            modal: false,
            visible: false,
            resizable: false
        }).data("kendoWindow");
    } else {
        // Empty the contents of the message window.
        messageWindow.empty();
    }
    return kendoWindow;
}